import { SocketService } from './socket.service';
import { SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { UserInfo, MessageType } from 'src/models/socket-io-model';
//import { Inject } from '@nestjs/common';

@WebSocketGateway()
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
    @WebSocketServer() socket_server: SocketIO.Server;

    constructor(
        private readonly socket_app_service: SocketService
    ) {
    }

    handleConnection(client: Socket, ...args: any[]) {
        let user_info = this.socket_app_service.regNewUser(client.id);
        console.log(`[${user_info.socket_code}] socket:Connection id:${user_info.id}.`);

        client.emit("conn-info", user_info);
    }

    handleDisconnect(client: Socket) {
        let user_index = this.socket_app_service.userLeave(client.id);
        console.log(`[${client.id}] socket:Disconnect id:${user_index}.`);
        client.server.emit("user-leave", { id: user_index });
    }


    @SubscribeMessage('set-nick-name')
    setNickName(client: Socket, { nick_name }: { nick_name?: string }): WsResponse<{ status: string }> {

        let user_info = this.socket_app_service.changeNickName(client.id, nick_name);
        if (user_info) {
            console.log(`socket [${client.id}]:set-nick-name '${nick_name}'`);
            client.broadcast.emit("user-changed", user_info);
        }

        return {
            event: "set-nick-name-ret",
            data: { status: "success" }
        };
    }

    @SubscribeMessage('enter-chat')
    enterChat(client: Socket, payload: any) {
        let user_info = this.socket_app_service.getUser(client.id);
        if (user_info) {
            client.broadcast.emit("user-enter", user_info);
        }
    }

    @SubscribeMessage('leave-chat')
    leaveChat(client: Socket, payload: any) {
        let user_info = this.socket_app_service.getUser(client.id);
        if (user_info) {
            client.broadcast.emit("user-leave", user_info);
        }
    }

    @SubscribeMessage('user-list')
    getUserList(client: Socket, payload: any) : WsResponse<UserInfo[]> {
        return {
            event:"user-list-ret",
            data: this.socket_app_service.getUserList()
        }
    }

    @SubscribeMessage('message-send')
    messageSend(client: Socket, payload: MessageType) {
        client.broadcast.emit("message-recv", payload);
    }

    @SubscribeMessage('message-send-to')
    messageSendTo(client: Socket, payload: MessageType) {
        if (payload.to_id) {
            let to_user = this.socket_app_service.getUser(payload.to_id)
            if(to_user && to_user.socket_code){
                client.server.to(to_user.socket_code).emit("message-recv", payload);
            }else{
                // 用户不存在
            }
        }
    }
}
